import { type TableInstance } from 'element-plus'
import { type Ref } from 'vue'

function getDeepObjValue<O extends object>(obj: O, keyStr: string) {
  if (!keyStr.includes('.')) {
    return Reflect.get(obj, keyStr)
  }
  const arr = keyStr.split('.')
  const key = arr.shift() as string
  const val = Reflect.get(obj, key)
  if (typeof val !== 'object') {
    return val
  }
  return getDeepObjValue(val as object, arr.join(','))
}

export default function useTableBatchAction<T extends object>(
  tableRef: Ref<TableInstance | undefined>,
  tableData: Ref<T[]> | T[],
  idFieldName = 'id'
) {
  const selectedIds = ref<string[]>([])
  const indeterminate = ref(false)
  const checkAll = ref(false)

  function handleTableSelectionChange(arr: T[]) {
    selectedIds.value = arr.map(item => {
      return getDeepObjValue(item, idFieldName)
    }) as string[]
    const total = Array.isArray(tableData)
      ? tableData.length
      : tableData.value.length
    indeterminate.value =
      selectedIds.value.length > 0 && selectedIds.value.length < total
    checkAll.value = selectedIds.value.length === total
  }

  function handleCheckAll() {
    if (tableRef.value) {
      tableRef.value.toggleAllSelection()
    }
  }

  function reset() {
    selectedIds.value = []
    checkAll.value = false
    indeterminate.value = false
  }

  return {
    selectedIds,
    indeterminate,
    checkAll,
    handleTableSelectionChange,
    handleCheckAll,
    reset
  }
}
